<?php
//声明CODE，获取小程序传过来的CODE
if(!isset($_POST["js_code"])){
    echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>"error"));
    exit;
}
$js_code = $_POST['js_code'];
$nickName = $_POST['nickName'];
$avatarUrl = $_POST['avatarUrl'];
$gender = $_POST['gender'];
$province = $_POST['province'];
$city = $_POST['city'];
$country = $_POST['country'];
//配置appid
$appid = "wxcc4c1c8f35ec207e";
//配置appscret
$secret = "f4b933055e9d49ef26a758dddd11ee33";
 
$url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$secret.'&js_code='.$js_code.'&grant_type=authorization_code';
$info = file_get_contents($url);//get请求网址，获取数据
$jsonObj = json_decode($info);//对json数据解码
if(isset($jsonObj->errcode)){
    echo json_encode(array("statusCode"=>0 , "data"=>null , "errMsg"=>$info));
    exit;
}
$openid = $jsonObj->openid;
$session_key = $jsonObj->session_key;
//echo json_encode(array("statusCode"=>0 , "data"=>$jsonObj , "errMsg"=>"success"));
include ("conn.php");
$sql = "SELECT * FROM user WHERE openid = '".$openid."'";
$result = $conn->query($sql);
if ($result->num_rows == 0) {
	//不存在openid帮他注册
	$sql1 = "INSERT INTO user (openid)
VALUES ('".$openid."');";
	$result1 = $conn->query($sql1);
}
//为这个openid生成3rd session_key并更新session_key和3rd session_key
$thirdSession=md5(mt_rand() . $openid);

$sql = "UPDATE user 
SET sessionKey='".$session_key."', thirdSession='".$thirdSession."', nickName='".$nickName."', avatarUrl='".$avatarUrl."', gender='".$gender."', province='".$province."', city='".$city."', country='".$country."' 
WHERE openid='".$openid."';";
$result = $conn->query($sql);

$sql ="SELECT id FROM user WHERE openid='".$openid."'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();

echo json_encode(['thirdSession'=>$thirdSession,'uid'=>$row['id']]); 
?>